//导入express包
const express = require('express')
//实例化router对象
const router = express.Router()

//导入数据操作
const { getAll, getById, exec } = require('../db/index')

router.get('/', async (req, res) => {
  var { page, size } = req.query
  var sql = `select count(*) as total from leavewords`
  const obj = await getById(sql)
  var offset = (page - 1) * size
  sql = `select * from leavewords limit ${offset},${size}`
  var data = await getAll(sql)
  if (data.length == 0) {
    page = page - 1
    offset = (page - 1) * size
    sql = `select * from leavewords limit ${offset},${size}`
    data = await getAll(sql)
  }
  res.send({
    code: 0,
    message: '获取博客成功',
    result: {
      total: obj.total,
      data: data
    },
    page: page
  })
})
router.get('/all', async (req, res) => {
  // 操作数据库
  let sql = `select * from leavewords ORDER BY create_time DESC limit 4`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '获取所有留言成功',
    result: {
      data: data
    }
  })
})
router.get('/search/LeaveWords', async (req, res) => {
  // 操作数据库
  const { page, size, searchMsg } = req.query
  let offset = (page - 1) * size
  let sql = `SELECT * from leavewords WHERE name LIKE '%${searchMsg}%' limit ${offset},${size}`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询留言成功',
    result: {
      data: data
    }
  })
})
//添加留言
router.post('/', async (req, res) => {
  const { name, content } = req.body
  let sql = `insert into leavewords values (null,'${name}',CURRENT_TIMESTAMP,'${content}')`
  try {
    let data = await exec(sql)
    res.send({
      code: 1,
      message: '添加留言成功'
    })
  } catch {
    res.send({
      code: 0,
      message: '添加留言失败'
    })
  }
})

//删除留言
router.delete('/:id', async (req, res) => {
  const id = req.params.id
  let sql = `delete from leavewords where id ='${id}' `
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '删除博客成功',
    data: data
  })
})
router.delete('/', async (req, res) => {
  const { selectLeaveWords } = req.body
  let sql = `delete from leavewords where id in (${selectLeaveWords})`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '删除博客成功',
    data: data
  })
})
//回复留言
router.put('/:id', async (req, res) => {
  const id = req.params.id
  const { replycontent } = req.body
  let sql = `update leavewords set replycontent='${replycontent}'where id = ${id}`
  try {
    const data = await exec(sql)
    res.send({
      code: 1,
      msg: '回复成功',
    })
  } catch {
    res.send({
      code: 0,
      msg: '回复失败'
    })
  }
})
module.exports = router
